package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.event.AfterOrderSaveEvent;
import com.iwhalecloud.bss.kite.cucc.order.util.RuleTriggerUtil;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItem;
import com.iwhalecloud.bss.kite.order.client.api.operate.ISaveOrderService;
import com.iwhalecloud.bss.kite.order.client.dto.OrderContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <Description> <br>
 * 订单受理流程：订单保存
 *
 * @author xiao.xuzhang<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2020年2月12日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl <br>
 */
@Component
public class OrderSaveHandler extends AbstractOrderHandler {

    @Resource
    private ISaveOrderService saveOrderService;

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public boolean canHandle(OrderRequest orderRequest) {
        if (Objects.equals(Boolean.TRUE, orderRequest.getPreCheck())) {
            // 订单预校验流程不入库
            return false;
        }

        return true;
    }

    @Override
    public void doHandle(OrderRequest orderRequest) {
        List<Map<String, Object>> orderInfoList = new ArrayList<>();
        List<OrderItem> orderItems = OrderContainer.ofRequest(orderRequest).listOrderItems();
        for (OrderItem orderItem : orderItems) {
            orderInfoList.add(KiteMapUtils.camelToUnderline(KiteMapUtils.beanToMap(orderItem)));
        }
        String custOrderId = orderRequest.getCustOrderId();
        String custId = orderRequest.getCustId();

        // 订单保存
        saveOrderService.save(orderRequest);

        // 订单保存后规则埋点
        RuleTriggerUtil.afOrderSaveRule(custOrderId, custId, orderInfoList, orderRequest);

        // 订单保存后事件埋点
        AfterOrderSaveEvent afterOrderSaveEvent = new AfterOrderSaveEvent(this, orderRequest);
        applicationContext.publishEvent(afterOrderSaveEvent);
    }
}
